home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
IRIX 6.5 Applications 2004 May
/
SGI IRIX 6.5 Applications 2004 May.iso
/
dev
/
java2_dev.idb
/
usr
/
demos
/
java2
/
JNI-invocation-example
/
invoke.c.z
/
invoke.c
Wrap
C/C++ Source or Header
|
2004-02-24
|
3KB
|
92 lines
/*
This demo example is based on an example taken from the Sun Java site.
See http://www.javasoft.com/docs/books/tutorial/native1.1
*/
#include <jni.h>
#include <malloc.h>
#include <stdlib.h>
#include "Prog.h"
main() {
JNIEnv *env;
JavaVM *jvm;
JDK1_1InitArgs vm_args;
jint res;
jclass cls;
jmethodID mid;
jstring jstr;
jobjectArray args;
char *env_classpath=(char *)0;
/* char *newclasspath=(char *)0; unused */
char *myclass="Prog";
char *mymethod="main";
char *mymethodsig="([Ljava/lang/String;)V";
/* IMPORTANT: specify vm_args version # if you use JDK1.1.2 and beyond */
vm_args.version = 0x00010002;
JNI_GetDefaultJavaVMInitArgs(&vm_args);
/* From 1.1.4 on, JNI_GetDefaultJavaVMInitArgs() sets the default
class path to contain the system classes. */
printf("\nDefault CLASSPATH is: %s\n\n", vm_args.classpath);
/*
* It is possible to modify the CLASSPATH any way we like here.
* Unfortunately, at this point is too late to set LD_LIBRARY_PATH
* or LD_LIBRARYN32_PATH. So our script did both jobs for us, and
* now we simply need to set the VM's class path from the
* environment.
*/
/* Check to see if the user has CLASSPATH set. */
env_classpath=getenv("CLASSPATH");
if (env_classpath) {
vm_args.classpath = env_classpath;
printf("\nNew CLASSPATH is: %s\n\n", vm_args.classpath);
} else {
printf("CLASSPATH is not set -- no user classes will be loaded.\n\n");
}
res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
if (res < 0) {
fprintf(stderr, "Can't create Java VM\n");
exit(1);
}
cls = (*env)->FindClass(env, myclass);
if (cls == 0) {
fprintf(stderr, "Can't find class %s.\n",myclass);
exit(1);
}
mid = (*env)->GetStaticMethodID(env, cls, mymethod, mymethodsig);
if (mid == 0) {
fprintf(stderr, "Can't find method %s.%s().\n",mymethod,myclass);
exit(1);
}
jstr = (*env)->NewStringUTF(env, "called from C!");
if (jstr == 0) {
fprintf(stderr, "Out of memory.\n");
exit(1);
}
args = (*env)->NewObjectArray(env, 1,
(*env)->FindClass(env, "java/lang/String"), jstr);
if (args == 0) {
fprintf(stderr, "Out of memory.\n");
exit(1);
}
printf("Calling Java method %s.%s()...\n" ,mymethod,myclass);
fflush(stdout);
(*env)->CallStaticVoidMethod(env, cls, mid, args);
printf("Returned from Java method %s.%s().\n" ,mymethod,myclass);
(*jvm)->DestroyJavaVM(jvm);
}